package com.wzq.upms.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

/**
 * the 集合 工具类
 * 
 * project：pub-core
 * 
 * $Author:Jeffy Chen
 * @version $Revision:$ 
 * @Modify $Date:$
 * @create time：2014-4-26 下午11:02:47
 *
 */
public class CollectionUtils {
	
	/**
	 * 抽取单一属性集合
	 * @param collection 集合
	 * @param propertyName 属性名
	 * @return List
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List fetchPropertyToList(Collection collection,
			String propertyName) throws Exception {
		if(collection == null){
			return null;
		}
		List list = new ArrayList();
		for (Iterator i$ = collection.iterator(); i$.hasNext();) {
			Object obj = i$.next();
			list.add(PropertyUtils.getProperty(obj, propertyName));
		}
		return list;
	}

	@SuppressWarnings("rawtypes")
	public static String fetchPropertyToString(Collection collection,
			String propertyName, String separator) throws Exception {
		if(collection == null){
			return null;
		}
		List list = fetchPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	public static <T, ID> void mergeByCheckedIds(Collection<T> collection,
			Collection<ID> checkedIds, Class<T> clazz) throws Exception {
		mergeByCheckedIds(collection, checkedIds, "id", clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T, ID> void mergeByCheckedIds(Collection<T> collection,
			Collection<ID> checkedIds, String idName, Class<T> clazz)
			throws Exception {
		if (checkedIds == null) {
			collection.clear();
			return;
		}
		Iterator<T> it = collection.iterator();
		while (it.hasNext()) {
			Object obj = it.next();
			if (checkedIds.contains(PropertyUtils.getProperty(obj, idName)))
				checkedIds.remove(PropertyUtils.getProperty(obj, idName));
			else
				it.remove();

		}
		for (Iterator<ID> i$ = checkedIds.iterator(); i$.hasNext();) {
			Object id = i$.next();
			Object obj = clazz.newInstance();
			PropertyUtils.setProperty(obj, idName, id);
			collection.add((T)obj);
		}
	}
	
	/**
	 * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
	 * 
	 * @param collection 来源集合.
	 * @param keyPropertyName 要提取为Map中的Key值的属性名.
	 * @param valuePropertyName 要提取为Map中的Value值的属性名.
	 */
	@SuppressWarnings("rawtypes")
	public static Map extractToMap(final Collection collection, final String keyPropertyName,
			final String valuePropertyName)  throws Exception {
		Map map = new HashMap(collection.size());
		for (Object obj : collection) {
			map.put(PropertyUtils.getProperty(obj, keyPropertyName),
					PropertyUtils.getProperty(obj, valuePropertyName));
		}
		return map;
	}
	
	/**
	 * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 * @param separator 分隔符.
	 */
	public static <T> String extractToString(final Collection<T> collection, final String propertyName, final String separator) throws Exception {
		List list = fetchPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
	 * @param collection 集合
	 * @param separator 分隔符
	 */
	public static <T> String convertToString(final Collection<T> collection, final String separator) throws Exception {
		return StringUtils.join(collection, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix，后面加入postfix，如<div>mymessage</div>。
	 * @param collection 集合
	 * @param prefix 前缀
	 * @param postfix 后缀
	 */
	public static <T> String convertToString(final Collection<T> collection, final String prefix, final String postfix) throws Exception {
		StringBuilder builder = new StringBuilder();
		for (Object o : collection) {
			builder.append(prefix).append(o).append(postfix);
		}
		return builder.toString();
	}

	/**
	 * 判断是否为空.
	 * @param collection 集合
	 */
	public static <T> boolean isEmpty(Collection<T> collection) throws Exception {
		return (collection == null || collection.isEmpty());
	}

	/**
	 * 取得Collection的第一个元素，如果collection为空返回null.
	 * @param collection 集合
	 */
	public static <T> T getFirst(Collection<T> collection) throws Exception {
		if (isEmpty(collection)) {
			return null;
		}
		return collection.iterator().next();
	}

	/**
	 * 获取Collection的最后一个元素 ，如果collection为空返回null.
	 * @param collection 集合
	 */
	public static <T> T getLast(Collection<T> collection) throws Exception {
		if (isEmpty(collection)) {
			return null;
		}
		//当类型为List时，直接取得最后一个元素 。
		if (collection instanceof List) {
			List<T> list = (List<T>) collection;
			return list.get(list.size() - 1);
		}
		//其他类型通过iterator滚动到最后一个元素.
		Iterator<T> iterator = collection.iterator();
		while (true) {
			T current = iterator.next();
			if (!iterator.hasNext()) {
				return current;
			}
		}
	}

	/**
	 * 返回a+b的新List.
	 * @param one 集合1
	 * @param other 集合2
	 */
	public static <T> List<T> union(final Collection<T> a, final Collection<T> b) throws Exception {
		List<T> result = new ArrayList<T>(a);
		result.addAll(b);
		return result;
	}

	/**
	 * 返回a-b的新List.
	 * @param one 集合1
	 * @param other 集合2
	 */
	public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) throws Exception {
		List<T> list = new ArrayList<T>(a);
		for (T element : b) {
			list.remove(element);
		}

		return list;
	}

	/**
	 * 返回a与b的交集的新List.
	 * @param one 集合1
	 * @param other 集合2
	 */
	public static <T> List<T> intersection(Collection<T> one, Collection<T> other) throws Exception {
		List<T> list = new ArrayList<T>();
		for (T element : one) {
			if (other.contains(element)) {
				list.add(element);
			}
		}
		return list;
	}
}
